package com.ywy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ywy.common.rest.Result;
import com.ywy.entity.Post;
import com.ywy.entity.UserCollection;
import com.ywy.service.PostService;
import com.ywy.service.UserCollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户收藏 前端控制器
 * </p>
 *
 * @author ywy
 * @since 2021-12-24
 */
@RestController
@RequestMapping("/collection")
public class UserCollectionController extends BaseController {
    @Autowired
    private UserCollectionService userCollectionService;
    @Autowired
    private PostService postService;

    /**
     * 判断用户是否收藏博客文章
     * @param pid
     * @return
     */
    @PostMapping("/find")
    public Result find(Integer pid) {
        // 根据文章id和用户id查询是否收藏
        QueryWrapper<UserCollection> queryWrapper = new QueryWrapper<UserCollection>()
                .eq("post_id", pid)
                .eq("user_id", getProfileId());
        int count = userCollectionService.count(queryWrapper);

        Map<String, Object> map = new HashMap<>(1);
        map.put("collection", count > 0);
        return Result.success(map);
    }

    /**
     * 收藏博客文章
     * @param pid
     * @return
     */
    @PostMapping("/add")
    public Result add(Integer pid) {
        // 查询文章是否存在
        Post post = postService.getById(pid);
        Assert.isTrue(post != null, "该文章已被删除");

        // 根据文章id和用户id查询是否收藏
        QueryWrapper<UserCollection> queryWrapper = new QueryWrapper<UserCollection>()
                .eq("post_id", pid)
                .eq("user_id", getProfileId());

        int count = userCollectionService.count(queryWrapper);
        if (count > 0) {
            return Result.failure("你已经收藏了");
        }

        // 如果没有收藏则进行收藏
        UserCollection collection = new UserCollection();
        collection.setUserId(getProfileId());
        collection.setPostId(pid);
        collection.setPostUserId(post.getUserId());
        userCollectionService.save(collection);

        return Result.success();
    }

    /**
     * 取消收藏博客文章
     * @param pid
     * @return
     */
    @PostMapping("/remove")
    public Result remove(Integer pid) {
        // 查询文章是否存在
        Post post = postService.getById(pid);
        Assert.isTrue(post != null, "该文章已被删除");

        // 根据文章id和用户id删除收藏
        QueryWrapper<UserCollection> queryWrapper = new QueryWrapper<UserCollection>()
                .eq("post_id", pid)
                .eq("user_id", getProfileId());
        userCollectionService.remove(queryWrapper);

        return Result.success();
    }
}
